﻿// Project: WebPage.Client, File: MyWebClient.cs
// Namespace: WebPage.Client, Class: MyWebClient
// Path: G:\Secure Project\WebCrawlerProject\WebPage.Client, Author: Radu-Mihail
// Code lines: 263, Size of file: 7.68 KB
// Creation date: 1/11/2009 3:03 PM
// Last modified: 1/11/2009 4:04 PM

// Author: Iulian Lita
// Project: WebPage
// Path: C:\Users\Tym\Documents\Visual Studio 2008\Projects\WebCrawlerProject\WebPage
// Creation date: 1/10/2009 11:04 PM
// Last modified: 1/11/2009 1:33 PM

#region Using directives
using System;
using System.Net;
using System.Text;
using WebPage;

#endregion

namespace WebPage.Client
{
    public enum WebPageContentType
    {
        TEXT,
        IMAGE,
        AUDIO,
        APPLICATION,
        VIDEO,
        MULTIPART,
        TEXTHTML,
        OTHER
    }

    /// <summary>
    /// Download Client
    /// </summary>
    public class MyWebClient : WebClient
    {
        #region Private fields
        /// <summary>
        /// _link response
        /// </summary>
        private HttpWebResponse _linkResponse = null;
        /// <summary>
        /// _link request
        /// </summary>
        private HttpWebRequest _linkRequest = null;
        /// <summary>
        /// _uri link
        /// </summary>
        private Uri _uriLink;
        /// <summary>
        /// _response uri
        /// </summary>
        private Uri _responseUri;

        #endregion

        #region Properties

        /// <returns>Content size</returns>
        public int ContentSize
        {
            get
            {
                return Convert.ToInt32(_linkResponse.Headers["Content-Length"]);
            }
        } // ContentSize

        /// <summary>
        /// Link base
        /// </summary>
        /// <returns>String</returns>
        public string HostLink
        {
            get 
            {
                return "http://" + _responseUri.Host;
            } // get
        } // LinkBase

        #endregion

        #region Constructor
        /// <summary>
        /// Create my web client
        /// </summary>
        /// <param name="webLink">Web link</param>
        /// <returns>Web client</returns>
        public MyWebClient(string webLink)
            : base()
        {

            try
            {
                _uriLink = new Uri(webLink);

                _linkRequest = (HttpWebRequest)base.GetWebRequest(new Uri(webLink));
                _linkResponse = (HttpWebResponse)base.GetWebResponse(_linkRequest);

                _responseUri = _linkResponse.ResponseUri;

                int status = (int)_linkResponse.StatusCode / 100;
                if (status == 4 || status == 5)
                    throw new Exception("Connection to web page " + webLink + " failed\n" + "Status code" + _linkResponse.StatusCode);



            } // try
            catch (Exception)
            {
                throw new Exception("Unable to connect to " + webLink);
            }

        } // MyWebClient(webLink)
        #endregion

        #region Public Methods


        /// <summary>
        /// Download data
        /// </summary>
        /// <returns></returns>
        public byte[] DownloadData()
        {
            return base.DownloadData(_responseUri);
        } // DownloadData()

        /// <summary>
        /// Download data string
        /// </summary>
        public string DownloadDataString()
        {
            return Encoding.ASCII.GetString(base.DownloadData(_responseUri));
        } // DownloadDataString()

        /// <summary>
        /// Returns the redirected link
        /// </summary>
        /// <returns>String</returns>
        public string RedirectLink()
        {
            return _responseUri.AbsoluteUri;
        } // RedirectLink()

        /// <summary>
        /// Initial link
        /// </summary>
        /// <returns>String</returns>
        public string InitialLink()
        {
            return _uriLink.AbsoluteUri;
        } // InitialLink()

        /// <summary>
        /// Get the last modified date
        /// </summary>
        /// <returns>The last modified date as a DateTime object</returns>
        public DateTime GetLastModifiedDate()
        {
            string date = _linkResponse.Headers["Last-Modified"];
            if (date == null)
                return DateTime.Now;
            else
                return Convert.ToDateTime(date);
        } // GetLastModifiedDate()

        /// <summary>
        /// Get last modified date as a string
        /// </summary>
        /// <returns>The date as a string in RFC 2822 format</returns>
        public string GetLastModifiedDateString()
        {
            string date = _linkResponse.Headers["Last-Modified"];
            if (date == null)
                return DateTime.Now.ToLocalTime().ToString();
            else
                return date;
        } // GetLastModifiedDateString()

        /// <summary>
        /// Get MIME type
        /// </summary>
        /// <returns>String</returns>
        public string GetMIMEType()
        {
            return _linkResponse.Headers["Content-Type"];
        } // GetMIMEType()

        /// <summary>
        /// Get content type
        /// </summary>
        /// <returns>Web page content type</returns>
        public WebPageContentType GetContentType()
        {
            string contentType = _linkResponse.Headers["Content-Type"];

            int generalTypeEnd = contentType.IndexOf('/');
            string generalType;
            if (-1 == generalTypeEnd)
                return WebPageContentType.OTHER;
            else
                generalType = contentType.Substring(0, generalTypeEnd);

            int subTypeEnd = contentType.IndexOf(';');
            string subType;
            if (-1 == subTypeEnd)
                subType = contentType.Substring(generalTypeEnd + 1);
            else subType = contentType.Substring(generalTypeEnd + 1, subTypeEnd - generalTypeEnd - 1);

            switch (generalType.ToLower())
            {
                case "text":
                    switch (subType.ToLower())
                    {
                        case "html":
                            return WebPageContentType.TEXTHTML;
                        default:
                            return WebPageContentType.TEXT;
                    }
                case "audio":
                    return WebPageContentType.AUDIO;
                case "application":
                    return WebPageContentType.APPLICATION;
                case "image":
                    return WebPageContentType.IMAGE;
                case "video":
                    return WebPageContentType.VIDEO;
                default:
                    return WebPageContentType.OTHER;
            } // switch

        } // GetContentType()
        #endregion

        #region Overriden methods

        /// <summary>
        /// Dispose
        /// </summary>
        /// <param name="disposing">Disposing</param>
        protected override void Dispose(bool disposing)
        {
            if(_linkResponse != null)
                _linkResponse.Close();
            base.Dispose(disposing);
        } // Dispose(disposing)

        /// <summary>
        /// Initialize component
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MyWebClient));
            // 
            // MyWebClient
            // 
            this.Headers = ((System.Net.WebHeaderCollection)(resources.GetObject("$this.Headers")));

        } // InitializeComponent()
        #endregion
    } // class MyWebClient
} // namespace WebPage
